package presentation;

import java.io.*;

import javax.imageio.stream.*;
import javax.servlet.*;
import javax.servlet.http.*;

 public class ViewImageServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String image = request.getParameter("image").trim();
		String size = request.getParameter("size");
		if(size != null) {
			size = size.trim();
		} else {
			size = "";
		}
		String path = this.getServletContext().getInitParameter("IMAGES_DIRECTORY");
		path = this.getServletContext().getRealPath(path);
		File imagesDir = new File(path);
		String[] filelist = imagesDir.list();
		boolean isImageFound = false;
		for(String file : filelist) {
			if(file.startsWith(image + ".")) {
				image = file;
				isImageFound = true;
				break;
			}
		}
		if(!isImageFound) {
			response.sendRedirect("Error.jsp?msg=imagenotfound");
			return;
		}
		String type = image.substring(image.lastIndexOf('.') + 1);
		if(type.equals("jpg")) {
			response.setContentType("image/jpeg");
		} else if(type.equals("png")) {
			response.setContentType("image/png");
		} else {
			response.setContentType("image/gif");
		}
		if(size.equalsIgnoreCase("s")) {
			image = "s_" + image;
		} else if(size.equalsIgnoreCase("m")) {
			image = "m_" + image;
		}
		FileImageInputStream fiis = new FileImageInputStream(new File(path + File.separatorChar + image));
		OutputStream out = response.getOutputStream();
		int oneByte;
		while((oneByte = fiis.read()) != -1) {
			out.write(oneByte);
		}
		out.flush();
		out.close();
	}  	  	  	    
}